package com.zdp.service;

import com.zdp.common.AuditStatusEnum;
import com.zdp.domain.Share;
import com.zdp.domain.dto.ShareAuditDTO;
import com.zdp.domain.dto.ShareDTO;
import com.zdp.domain.dto.UserDTO;
import com.zdp.domain.message.UserAddBonusMsgDTO;
import com.zdp.feignclient.UserCenterFeignClient;
import com.zdp.mapper.ShareMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Objects;

/**
 * @author sesshomaru
 * @date 2021/10/4 22:08
 */
@Slf4j
@Service
public class ShareService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private ShareMapper shareMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private UserCenterFeignClient userCenterFeignClient;

    public ShareDTO findById(Integer id) {
        // 获取分享
        Share share = this.shareMapper.selectById(id);
        // 获取分享的用户id
        Integer userId = share.getUserId();

        // 方式一 根据用户id请求用户服务查询用户信息
       /* ResponseEntity<UserDTO> forEntity = restTemplate.getForEntity(
                "http://localhost:8080/users/{id}",
                UserDTO.class, userId);
        UserDTO userDTO = forEntity.getBody();*/

        // 方式二 通过DiscoveryClient请求用户服务查询用户信息
       /* List<ServiceInstance> instances = discoveryClient.getInstances("user-center");
        String targetUrl = instances.stream()
                .map(instance -> instance.getUri().toString() + "/users/{id}")
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("当前没有实例"));
        log.info("请求的目标地址:{}", targetUrl);

        ResponseEntity<UserDTO> forEntity = restTemplate.getForEntity(
                targetUrl,
                UserDTO.class, userId);
        UserDTO userDTO = forEntity.getBody();*/

        // 方式三 使用ribbon的方式请求用户服务查询用户信息
       /* ResponseEntity<UserDTO> forEntity = this.restTemplate.getForEntity("http://user-center/users/{id}", UserDTO.class, userId);
        UserDTO userDTO = forEntity.getBody();*/

        // 方法四 使用feign的方式请求用户服务查询用户信息
        UserDTO userDTO = userCenterFeignClient.findById(userId);

        ShareDTO shareDTO = new ShareDTO();
        BeanUtils.copyProperties(share, shareDTO);

        shareDTO.setWxNickName(userDTO.getWxNickname());

        return shareDTO;
    }

    public Share auditById(Integer id, ShareAuditDTO shareAuditDTO) {
        // 1. 查询share是否存在, 不存在或者当前的审核状态不是待审核 则抛出异常
        Share share = shareMapper.selectById(id);
        if (share == null) {
            throw new IllegalArgumentException("参数非法,该分享不存在");
        }
        if (!Objects.equals("NOT_YET", share.getAuditStatus())) {
            throw new IllegalArgumentException("参数非法! 该分享已审核通过或者审核不通过");
        }
        // 2. 审核资源，将状态设置为PASS/REJECT
        share.setAuditStatus(shareAuditDTO.getAuditStatusEnum().toString());
        this.shareMapper.updateById(share);

        // 3. 如果是PASS为发布人添加积分
        if (AuditStatusEnum.PASS.equals(shareAuditDTO.getAuditStatusEnum())) {
            this.rocketMQTemplate.convertAndSend("add-bonus-topic",
                    UserAddBonusMsgDTO.builder()
                            .userId(share.getUserId())
                            .bonus(50)
                            .build()
            );
        }

        return share;
    }
}
